#!/usr/bin/env bash
# 实例文件：load_mp3
# 尽可能多地向mp3播放器中填装歌曲
# 这里假设mp3播放器挂载在/media/mp3上

#
# 确定文件大小
#
function FILESIZE()
{
    FN=${1:-/dev/null}
    if [[ -e $FN ]]
    then
        set -- $(ls -s "$FN")
        FZ=$1
    fi
}
#
# 计算mp3播放器的可用存储空间
#
function FREESPACE()
{
    set -- $(df /media/mp3 | grep '^/dev/')
    FREE=$4
}

# 从全局可用存储中减去给定文件大小
function REDUCE()
((  FREE-=${1:-0}))

#
# 主体部分
#
let SUM=0
let COUNT=0
export FZ
export FREE
FREESPACE
find . -name '*.mp3' -print | \
( while read PATHNM
      do
          FILESIZE "$PATHNM"
          if ((FZ <= FREE))
          then
              echo loading $PATHNM
              cp "$PATHNM" /media/mp3
              if (( $? == 0 ))
              then
                  let SUM+=FZ
                  let COUNT++
                  REDUCE $FZ
              else
                  echo "bad copy of $PATHNM to /media/mp3"
                  rm -f /media/mp3/"${PATNNM##*/}"
                  FREESPACE
              fi
              if (( FREE <= 0 ))
              then
                  break
              fi
          else
              echo skipping $PATHNM
          fi
      done
      printf "loaded %d songs (%d blocks)" $COUNT $SUM
      printf " onto /media/mp3 (%d blocks free)\n" $FREE
)

